<script setup>
import { ref, onMounted, nextTick } from 'vue'
import { ElMessage, ElIcon } from 'element-plus'
import logger from '@/utils/logger'
import { fetchMyOnlineGoods } from '@/api/goodsRemovalApi'

// 使用defineModel替代props和emit
const selectedGoods = defineModel('modelValue', {
  type: Array,
  default: () => [],
})

const emit = defineEmits(['close'])

// 表格数据和加载状态
const tableData = ref([])
const loading = ref(false)
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)

// 查询条件
const queryFields = ref({
  goodsName: '',
  goodsTypeName: '',
})

// 表格引用，用于操作表格选择
const tableRef = ref(null)

// 获取库存商品列表
const fetchStoreData = async () => {
  loading.value = true
  try {
    const params = {
      queryFields: {
        goodsName: queryFields.value.goodsName,
        goodsTypeName: queryFields.value.goodsTypeName,
      },
      currentPage: currentPage.value,
      pageSize: pageSize.value,
    }
    const res = await fetchMyOnlineGoods(params)

    if (res.success) {
      tableData.value = res.data.list || []
      total.value = res.data.total || 0

      // 在表格数据更新后应用选中状态
      nextTick(() => {
        applySelection()
      })
    } else {
      ElMessage.error('获取库存商品列表失败')
    }
  } catch (error) {
    logger.error('获取库存商品列表失败', error)
    ElMessage.error('获取库存商品列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索
const handleSearch = () => {
  currentPage.value = 1
  fetchStoreData()
}

// 重置搜索
const resetSearch = () => {
  queryFields.value = {
    goodsName: '',
    goodsTypeName: '',
  }
  currentPage.value = 1
  fetchStoreData()
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchStoreData()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchStoreData()
}

// 应用已选商品到表格
const applySelection = () => {
  if (!tableRef.value) return

  // 清除当前表格的选中状态
  tableRef.value.clearSelection()

  // 获取当前页的行数据
  const currentPageRows = tableData.value || []

  // 遍历当前页的行，如果该行商品在已选列表中，则设置为选中状态
  currentPageRows.forEach((row) => {
    const isSelected = selectedGoods.value.some(
      (selected) => String(selected.dealerGoodsStoreId) === String(row.dealerGoodsStoreId),
    )
    if (isSelected) {
      tableRef.value.toggleRowSelection(row, true)
    }
  })
}

// 处理表格选择变化
const handleSelectionChange = (selection) => {
  // 获取当前页的所有行数据
  const currentPageRows = tableData.value || []

  // 创建一个Map来存储当前页的选中状态
  const currentPageSelectionMap = new Map()
  selection.forEach((item) => {
    currentPageSelectionMap.set(String(item.dealerGoodsStoreId), item)
  })

  // 更新selectedGoods，保持其他页面的选中状态不变
  const newSelectedGoods = selectedGoods.value.filter((item) => {
    // 如果商品不在当前页，保持其选中状态
    return !currentPageRows.some(
      (row) => String(row.dealerGoodsStoreId) === String(item.dealerGoodsStoreId),
    )
  })

  // 添加当前页新选中的商品
  selection.forEach((item) => {
    newSelectedGoods.push(item)
  })

  selectedGoods.value = newSelectedGoods
}

// 确认选择
const handleConfirm = () => {
  emit('close')
}

// 取消选择
const handleCancel = () => {
  emit('close')
}

onMounted(() => {
  fetchStoreData()
})
</script>

<template>
  <div class="goods-selector">
    <!-- 搜索区域 -->
    <div class="search-container">
      <el-form :inline="true" :model="queryFields">
        <el-form-item label="商品名称">
          <el-input
            v-model="queryFields.goodsName"
            placeholder="请输入商品名称"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item label="商品类别">
          <el-input
            v-model="queryFields.goodsTypeName"
            placeholder="请输入商品类别"
            clearable
            style="width: 200px"
            @keyup.enter="handleSearch"
          >
            <template #prefix>
              <el-icon><LineMdSearch /></el-icon>
            </template>
          </el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <template #icon>
              <el-icon><LineMdSearch /></el-icon>
            </template>
            搜索
          </el-button>
          <el-button @click="resetSearch">
            <template #icon>
              <el-icon><LineMdClose /></el-icon>
            </template>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </div>

    <!-- 表格区域 -->
    <div class="table-wrapper">
      <el-table
        ref="tableRef"
        v-loading="loading"
        :data="tableData && tableData.length > 0 ? tableData : [{}]"
        style="width: 100%"
        @selection-change="handleSelectionChange"
        row-key="dealerGoodsStoreId"
        reserve-selection
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="图片" width="80" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              <el-image
                v-if="row.goodsPicture"
                :src="row.goodsPicture"
                style="width: 50px; height: 50px; border-radius: 4px"
                :preview-src-list="[row.goodsPicture]"
                fit="cover"
                preview-teleported
              />
              <div v-else class="no-image">无图片</div>
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column
          prop="goodsName"
          label="商品名称"
          min-width="150"
          show-overflow-tooltip
          align="center"
        >
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.goodsName || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column prop="dealerGoodsTypeName" label="商品类别" min-width="120" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.dealerGoodsTypeName || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column prop="xzqhName" label="专属区域" min-width="120" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.xzqhName || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column prop="specifications" label="规格" min-width="120" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.specifications || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column prop="unitPrice" label="单价（元）" min-width="120" align="center" />
        <el-table-column prop="unit" label="单位" min-width="80" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.unit || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
        <el-table-column prop="address" label="产地" min-width="120" align="center">
          <template #default="{ row }">
            <template v-if="tableData && tableData.length > 0">
              {{ row.address || '-' }}
            </template>
            <template v-else> - </template>
          </template>
        </el-table-column>
      </el-table>
      <!-- 分页区域 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 30, 50]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </div>

    <!-- 操作按钮 -->
    <div class="action-container">
      <el-button @click="handleCancel">
        <template #icon>
          <el-icon><LineMdClose /></el-icon>
        </template>
        取消
      </el-button>
      <el-button type="primary" @click="handleConfirm">
        <template #icon>
          <el-icon><LineMdPlus /></el-icon>
        </template>
        确认选择
      </el-button>
    </div>
  </div>
</template>

<style lang="scss" scoped>
.goods-selector {
  display: flex;
  flex-direction: column;
  height: 100%;
  padding: 10px;
  height: calc(100vh - 200px);
  gap: 10px;

  .search-container {
    border: 1px solid #ebeef5;
    border-radius: 10px;
    padding: 15px 15px 0;
    background-color: #fff;
  }

  .table-wrapper {
    flex: 1;
    overflow: auto;
    display: flex;
    flex-direction: column;
    justify-content: space-between;
    gap: 10px;
    background-color: #fff;
    padding: 15px;
    border-radius: 10px;

    .pagination-container {
      display: flex;
      justify-content: center;
      margin-top: 10px;
    }
  }

  .action-container {
    display: flex;
    justify-content: flex-end;
    padding: 10px;
    background-color: #fff;
    border-radius: 10px;
    gap: 16px;
  }

  .no-image {
    width: 50px;
    height: 50px;
    display: flex;
    align-items: center;
    justify-content: center;
    color: #909399;
    background-color: #f5f7fa;
    font-size: 12px;
    border-radius: 4px;
    border: 1px dashed #d9d9d9;
  }
}
</style>
